<template>
  <div class="app-container">
    <div class="header">
      <div class="drag-box" draggable="true">
        <h1>我的待办事项</h1>
      </div>
      <div class="fix-button">
        <el-button circle @click="toggleFix">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" :fill="isFixed?'#4CAF50':'#333'" viewBox="0 0 16 16" id="fix-icon">
            <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zm.5 3a.5.5 0 0 0-1 0v5.793l-2.146-2.147a.5.5 0 0 0-.708.708l3 3a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 8.793V3z"/>
          </svg>
        </el-button>
        <span class="tooltip" id="fix-tooltip">{{isFixed?'取消固定':'固定位置'}}</span>
      </div>
    </div>
    <!-- 添加/修改弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      title="新增任务/修改任务"
      width="500"
      class="dialog-class"
      :before-close="ev_closePop"
    >
      <el-form :model="newTask" :rules="newTaskRules" ref="addFormRef">
        <el-form-item label="任务描述" prop="title">
          <el-input v-model="newTask.title" placeholder="输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务级别" prop="category">
          <el-select
            v-model="newTask.category"
            placeholder="请选择任务级别"
            size="large"
          >
            <el-option
              v-for="item in taskLevelOp"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预期完成时间" prop="dueDate">
          <el-date-picker
              v-model="newTask.dueDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ev_closePop()">取消</el-button>
          <el-button type="primary" @click="submitForm(addFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="btn-box">
      <el-button type="primary" @click="formType='add',ev_openPop()">新增任务</el-button>
    </div>
    <div class="task-box">
      <el-scrollbar view-class="task-scroll">
        <div v-for="level in taskLevelOp" :key="level.value" class="task-item">
          <div class="task-level-label">{{ level.label }}</div>
          <div class="task-list">
            <el-scrollbar>
              <el-card v-for="task in filteredTasks(level.value)">
                <div>{{ task.title }}</div>
                <div>创: {{ formatDate(task.createdAt) }}</div>
                <div>改: {{ formatDate(task.modifiedAt) }}</div>
                <div>预: {{ task.dueDate }}</div>
                <div>
                  <el-button @click="editTask(task)">编辑</el-button>
                  <el-button type="danger" @click="deleteTask(task.id)">删除</el-button>
                </div>
              </el-card>
            </el-scrollbar>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="time-display" id="current-time">{{ currentTime }}</div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onUnmounted, shallowReactive, toRaw } from 'vue';
import {  ElMessageBox, ElNotification } from 'element-plus';
// 任务列表
const tasks = reactive([]);
// 当前选中
const activeCategory = ref('重要紧急');

// 新增/修改弹窗
const dialogVisible=ref(false)
// add/edit
const formType=ref('add')
const newTask = ref({
  title: '',
  dueDate: '',
  category: ''
});
const taskLevelOp=[
  {label:'重要且紧急',value:'1'},
  {label:'紧急不重要',value:'2'},
  {label:'重要不紧急',value:'3'},
  {label:'不重要不紧急',value:'4'},
]
const newTaskRules = reactive({
  title: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
  ],
  category: [
    { required: true, message: '请选择任务级别', trigger: ['blur','change'] },
  ],
  dueDate: [
    { required: true, message: '请选择任务截止日期', trigger: ['blur','change'] },
  ],
})


const isFixed = ref(false);
// 提醒列表
let reminders = [];

// 从 localStorage 加载任务
const loadTasks = () => {
  const savedTasks = localStorage.getItem('tasks');
  if (savedTasks) {
    const loadedTasks = JSON.parse(savedTasks);
    loadedTasks.forEach(task => {
      if (task.createdAt) {
        task.createdAt = new Date(task.createdAt);
      }
      if (task.modifiedAt) {
        task.modifiedAt = new Date(task.modifiedAt);
      }
      tasks.push(task);
    });
  }
};

// 保存任务到 localStorage
const saveTasks = () => {
  localStorage.setItem('tasks', JSON.stringify(
    tasks.map(task => ({
      ...task,
      createdAt: task.createdAt ? task.createdAt.toISOString() : null,
      modifiedAt: task.modifiedAt ? task.modifiedAt.toISOString() : null
    }))
  ));
};

const ev_openPop=()=>{
  dialogVisible.value=true
}


const addFormRef=ref(null)
// 重置表单
const ev_closePop=()=>{
  addFormRef.value.resetFields()
  dialogVisible.value=false
}
// 提交任务表单
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      if(formType.value==='add'){
        tasks.push({
          id:Date.now(),
          createdAt: new Date(),
          modifiedAt: new Date(),
          ...newTask.value,
        });
      }else{
        let idx=tasks.findIndex(item=>item.id===newTask.value.id)
        if(idx!=-1){
          let {createdAt,id}=tasks[idx]
          tasks[idx]={
            id,createdAt,modifiedAt: new Date(),...newTask.value
          }
        }
      }
      ev_closePop()
      // 保存到本地存储
      saveTasks();
      ElNotification.success(formType.value==='add'?'添加成功':'修改成功')
    }
  })
};

// 编辑任务
const editTask = (data) => {
  newTask.value={...data}
  formType.value='edit'
  ev_openPop()
};

// 删除任务
const deleteTask = (id) => {
  ElMessageBox.confirm('确定要删除这个任务吗？', '删除任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let index=tasks.findIndex(item=>item.id===id)
    if(index!=-1){
      tasks.splice(index, 1);
      saveTasks();
      ElNotification.success('任务已删除');
    }else{
      ElNotification.error('找不到该任务')
    }
  }).catch(() => {
    // 取消删除
  });
};

// 过滤当前分类的任务
const filteredTasks = (level) => {
  return tasks.filter(task => task.category === level);
};
// 切换固定状态
const toggleFix = () => {
  isFixed.value = !isFixed.value;
  window.api.send('toggle-fix', isFixed.value);
};

// 监听主进程发送的固定状态
window.api.receive('fix-status', (event, status) => {
  isFixed.value = status;
});

// 更新当前时间显示
const currentTime=ref('')
let lastSecond = new Date().getSeconds();
const updateCurrentTime = () => {
  const now = new Date();
  if (now.getSeconds() !== lastSecond) {
    lastSecond = now.getSeconds();
    currentTime.value = now.toLocaleString();
  }
  requestAnimationFrame(updateCurrentTime);
};
// 初始化
onMounted(() => {
  loadTasks();
  // 定时更新时间和检查提醒
  updateCurrentTime()
});
// 组件卸载时清除定时器
onUnmounted(() => {
  reminders.forEach((timeout) => clearTimeout(timeout));
});
// 监听任务更新
watch(tasks, () => {
  console.log('任务列表更新');
  // 发送任务数据到主进程，由主进程管理提醒
  window.api.send('update-tasks', toRaw(tasks));
}, { deep: true });

// 格式化日期为可读形式
const formatDate = (date) => {
  if (!date) return '';
  return new Date(date).toLocaleString();
};
</script>

<style scoped lang="scss">
.app-container {
    width: 100%;
    height: 600px;
    padding: 20px;
    box-sizing: border-box;
    background-color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border-radius: 15px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .drag-box{
      flex: 1;
      cursor: move;
      -webkit-app-region: drag;
    }
    .fix-button {
      flex-shrink: 0;
    }
}

.time-display {
    position: absolute;
    bottom: 5px;
    right: 10px;
    font-size: 14px;
    color: #666;
}



.tooltip {
    position: absolute;
    top: -30px;
    left: 0;
    background-color: #333;
    color: white;
    padding: 5px 10px;
    border-radius: 5px;
    font-size: 12px;
    opacity: 0;
    transition: opacity 0.3s;
    pointer-events: none;
    white-space: nowrap;
    z-index: 10;
}

.el-button {
    margin-right: 5px;
}




.dialog-class{

}

.btn-box{
  margin-bottom: 20px;
}
.task-box{
  overflow: scroll;
  &::-webkit-scrollbar{
    width: 0;
    height: 0;
  }
  :deep(.task-scroll){
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }
  .task-item {
    flex: 1;
    min-width: 235px;
    height: 450px;
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
    padding: 15px;
    background: #f0f0f0; /* 设置背景颜色，可选 */
    border: solid 2px transparent;
    border-radius: 10px;
    background-image: linear-gradient(#fff, #fff), linear-gradient(135deg, rgba(183, 40, 255, 1), rgba(40, 112, 255, 1));
    background-origin: border-box;
    background-clip: padding-box, border-box;
    &::-webkit-scrollbar{
      width: 0;
      height: 0;
    }
    .task-level-label{
      font-size: 14px;
      line-height: 20px;
      font-weight: bold;
      background: linear-gradient(to bottom, #1a2a6c, #b21f1f);
      -webkit-background-clip: text;
      background-clip: text;
      color: transparent;
      flex-shrink: 0;
      margin-bottom: 20px;
    }
    .task-list{
      height: 100%;
      flex: 1;
      overflow-y: scroll;
      :deep(.el-scrollbar__view){
        display: flex;
        flex-direction: column;
        gap: 20px;
        .el-card__body{
          padding: 10px;
          display: flex;
          flex-direction: column;
          gap: 5px;
        }
      }
      
      &::-webkit-scrollbar{
        width: 0;
        height: 0;
      }
    }
  }
}
</style>